﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfSnqkGasAnalysis.IData;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis.IData_impl
{
    /// <summary>
    /// 特殊报告。数据接口实现。
    /// </summary>
    /// 创建时间：2022-12-15 16:20:46。作者：王浩力
    public class Teshu_gasDAL_impl : BaseDAL, ITeshu_gasDAL
    {
        public IResult Add(Teshu_gas teshu_Gas)
        {
            Snowflake snowflake = new Snowflake(1, 1);
            string sql = @$"INSERT INTO teshu_gas (
                          id,
                          report_no,
                          well_no,
                          well_deep,
                          sample_temperature,
                          top_boundary,
                          bottom_boundary,
                          oil_pressure,
                          casing_pressure,
                          sampling_location,
                          client,
                          sampler,
                          analyst,
                          sampling_unit,
                          sampling_time,
                          input_real_name,
                          input_user_id,
                          input_time,
 
                          o_step
                      )
                      VALUES (
                          { teshu_Gas.Id },
                          $report_no,
                          $well_no,
                          $well_deep,
                          $sample_temperature,
                          $top_boundary,
                          $bottom_boundary,
                          $oil_pressure,
                          $casing_pressure,
                          $sampling_location,
                          $client,
                          $sampler,
                          $analyst,
                          $sampling_unit,
                          $sampling_time,
                          $input_real_name,
                          $input_user_id,
                          $input_time, 
                          1
                      );
";
            Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
            keyValuePairs.Add("$report_no", teshu_Gas.Report_no);
            keyValuePairs.Add("$well_no", teshu_Gas.Well_no);
            keyValuePairs.Add("$well_deep", teshu_Gas.Well_deep);
            keyValuePairs.Add("$sample_temperature", teshu_Gas.Sample_temperature);
            keyValuePairs.Add("$top_boundary", teshu_Gas.Top_boundary);
            keyValuePairs.Add("$bottom_boundary", teshu_Gas.Bottom_boundary);
            keyValuePairs.Add("$oil_pressure", teshu_Gas.Oil_pressure);
            keyValuePairs.Add("$casing_pressure", teshu_Gas.Casing_pressure);
            keyValuePairs.Add("$sampling_location", teshu_Gas.Sampling_location);
            keyValuePairs.Add("$client", teshu_Gas.Client);
            keyValuePairs.Add("$sampler", teshu_Gas.Sampler);
            keyValuePairs.Add("$analyst", teshu_Gas.Analyst);
            keyValuePairs.Add("$sampling_unit", teshu_Gas.Sampling_unit);
            keyValuePairs.Add("$sampling_time", teshu_Gas.Sampling_time);
            keyValuePairs.Add("$input_real_name", teshu_Gas.Input_real_name);
            keyValuePairs.Add("$input_user_id", teshu_Gas.Input_user_id);
            keyValuePairs.Add("$input_time", teshu_Gas.Input_time);
            //keyValuePairs.Add("$del_time", teshu_Gas.Del_time);
            //keyValuePairs.Add("$proofread_real_name", teshu_Gas.Proofread_real_name);
            //keyValuePairs.Add("$proofread_time", teshu_Gas.Proofread_time);

            //日志表保存
            sql += $@"INSERT INTO teshu_gas_update_log (
                                     id,
                                     teshu_gas_key,
                                     report_no,
                                     well_no,
                                     well_deep,
                                     sample_temperature,
                                     top_boundary,
                                     bottom_boundary,
                                     oil_pressure,
                                     casing_pressure,
                                     sampling_location,
                                     client,
                                     sampler,
                                     analyst,
                                     sampling_unit,
                                     sampling_time,
                                     input_real_name,
                                     input_user_id,
                                     input_time,             
                                     data_version
                                 )
                                 VALUES(
                                     {snowflake.NextId()},
                                     {teshu_Gas.Id},
                                     $K_report_no,
                                     $K_well_no,
                                     $K_well_deep,
                                     $K_sample_temperature,
                                     $K_top_boundary,
                                     $K_bottom_boundary,
                                     $K_oil_pressure,
                                     $K_casing_pressure,
                                     $K_sampling_location,
                                     $K_client,
                                     $K_sampler,
                                     $K_analyst,
                                     $K_sampling_unit,
                                     $K_sampling_time,
                                     $K_input_real_name,
                                     $K_input_user_id,
                                     $K_input_time,                           
                                     1
                                 );
            ";
            keyValuePairs.Add("$K_report_no", teshu_Gas.Report_no);
            keyValuePairs.Add("$K_well_no", teshu_Gas.Well_no);
            keyValuePairs.Add("$K_well_deep", teshu_Gas.Well_deep);
            keyValuePairs.Add("$K_sample_temperature", teshu_Gas.Sample_temperature);
            keyValuePairs.Add("$K_top_boundary", teshu_Gas.Top_boundary);
            keyValuePairs.Add("$K_bottom_boundary", teshu_Gas.Bottom_boundary);
            keyValuePairs.Add("$K_oil_pressure", teshu_Gas.Oil_pressure);
            keyValuePairs.Add("$K_casing_pressure", teshu_Gas.Casing_pressure);
            keyValuePairs.Add("$K_sampling_location", teshu_Gas.Sampling_location);
            keyValuePairs.Add("$K_client", teshu_Gas.Client);
            keyValuePairs.Add("$K_sampler", teshu_Gas.Sampler);
            keyValuePairs.Add("$K_analyst", teshu_Gas.Analyst);
            keyValuePairs.Add("$K_sampling_unit", teshu_Gas.Sampling_unit);
            keyValuePairs.Add("$K_sampling_time", teshu_Gas.Sampling_time);
            keyValuePairs.Add("$K_input_real_name", teshu_Gas.Input_real_name);
            keyValuePairs.Add("$K_input_user_id", teshu_Gas.Input_user_id);
            keyValuePairs.Add("$K_input_time", teshu_Gas.Input_time);

            string error = null;
            int count = ExecSqlCmd(sql, keyValuePairs, c =>
             {
                 return c.ExecuteNonQuery();
             }, ex => { error = ex.Message; });
            if (count > 0)
            {
                return new ResultSuccess("新增成功");
            }
            return new Result("新增出错，" + error);
        }

        public IResult Delete(Teshu_gas teshu_Gas)
        {
            string sql = $"update  Teshu_gas  set    del_time='{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}'  where id={teshu_Gas.Id} ";
            string error = null;
            int count = ExecSqlCmd(sql, null, c =>
            {
                return c.ExecuteNonQuery();
            }, ex => { error = ex.Message; });
            return count > 0 ? new ResultSuccess("删除成功") : new Result("删除失败," + error);
        }

        public IResult Edit(Teshu_gas teshu_Gas)
        {
            //查询版本号
            string sqlVersion = "select  data_version  from  teshu_gas_update_log  where  teshu_gas_key=" + teshu_Gas.Id;
            long? dataVersion = ExecSqlCmd(sqlVersion, null, c =>
             {
                 var obj = c.ExecuteScalar();
                 return obj.ToMyInt64();
             });
            dataVersion = dataVersion == 0 ? 1 : dataVersion + 1;

            //校对处理
            string sqlColumn = "";
            if (teshu_Gas.Proofread_real_name?.Length > 0)
            {
                sqlColumn = ",Proofread_user_id=$Proofread_user_id,proofread_real_name=$proofread_real_name,proofread_time=$proofread_time";
            }

            Snowflake snowflake = new Snowflake(1, 1);
            string sql = $@" UPDATE  teshu_gas
   SET
       report_no = $report_no,
       well_no = $well_no,
       well_deep = $well_deep,
       sample_temperature = $sample_temperature,
       top_boundary = $top_boundary,
       bottom_boundary = $bottom_boundary,
       oil_pressure = $oil_pressure,
       casing_pressure = $casing_pressure,
       sampling_location = $sampling_location,
       client = $client,
       sampler = $sampler,
       analyst = $analyst,
       sampling_unit = $sampling_unit,
       sampling_time = $sampling_time,
        o_step=$oStep
{sqlColumn}
 WHERE id = " + teshu_Gas.Id + ";";

            Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
            keyValuePairs.Add("$report_no", teshu_Gas.Report_no);
            keyValuePairs.Add("$well_no", teshu_Gas.Well_no);
            keyValuePairs.Add("$well_deep", teshu_Gas.Well_deep);
            keyValuePairs.Add("$sample_temperature", teshu_Gas.Sample_temperature);
            keyValuePairs.Add("$top_boundary", teshu_Gas.Top_boundary);
            keyValuePairs.Add("$bottom_boundary", teshu_Gas.Bottom_boundary);
            keyValuePairs.Add("$oil_pressure", teshu_Gas.Oil_pressure);
            keyValuePairs.Add("$casing_pressure", teshu_Gas.Casing_pressure);
            keyValuePairs.Add("$sampling_location", teshu_Gas.Sampling_location);
            keyValuePairs.Add("$client", teshu_Gas.Client);
            keyValuePairs.Add("$sampler", teshu_Gas.Sampler);
            keyValuePairs.Add("$analyst", teshu_Gas.Analyst);
            keyValuePairs.Add("$sampling_unit", teshu_Gas.Sampling_unit);
            keyValuePairs.Add("$sampling_time", teshu_Gas.Sampling_time);
            keyValuePairs.Add("$oStep", teshu_Gas.O_step);

            if (teshu_Gas.Proofread_real_name?.Length > 0)
            {
                keyValuePairs.Add("$proofread_real_name", teshu_Gas.Proofread_real_name);
                keyValuePairs.Add("$proofread_time", teshu_Gas.Proofread_time);

                //校对人id，        添加时间：2023-1-8 23:58:40。
                keyValuePairs.Add("$Proofread_user_id", teshu_Gas.Proofread_user_id);
            }

            //判断是否修改了字段值。修改了记录日志
            var old = Get(teshu_Gas.Id);
            old.O_step = 0;
            old.Input_user_id = 0;
            old.Input_real_name = "";
            old.Proofread_real_name = "";
            old.Proofread_time = "";
            old.Proofread_user_id = 0;
            old.Del_time = "";
            old.Input_time = null;

            //新的
            var newInfo = JsonMyHandle.CopyObject<Teshu_gas>(teshu_Gas);
            newInfo.O_step = 0;
            newInfo.Input_time = null;
            newInfo.Input_user_id = 0;
            newInfo.Input_real_name = "";
            newInfo.Proofread_real_name = "";
            newInfo.Proofread_time = "";
            newInfo.Proofread_user_id = 0;
            newInfo.Del_time = "";
            string json1 = JsonMyHandle.ToJsonStr(old);
            string json2 = JsonMyHandle.ToJsonStr(newInfo);
            if (!json1.Equals(json2))
            {
                sql += $@"INSERT INTO teshu_gas_update_log (
                                     id,
                                     teshu_gas_key,
                                     report_no,
                                     well_no,
                                     well_deep,
                                     sample_temperature,
                                     top_boundary,
                                     bottom_boundary,
                                     oil_pressure,
                                     casing_pressure,
                                     sampling_location,
                                     client,
                                     sampler,
                                     analyst,
                                     sampling_unit,
                                     sampling_time,                                
                                     update_real_name,
                                     update_time,
                                     data_version
                                 )
                                 VALUES(
                                     {snowflake.NextId()},
                                     {teshu_Gas.Id},
                                     $K_report_no,
                                     $K_well_no,
                                     $K_well_deep,
                                     $K_sample_temperature,
                                     $K_top_boundary,
                                     $K_bottom_boundary,
                                     $K_oil_pressure,
                                     $K_casing_pressure,
                                     $K_sampling_location,
                                     $K_client,
                                     $K_sampler,
                                     $K_analyst,
                                     $K_sampling_unit,
                                     $K_sampling_time,                  
                                     $K_update_real_name,
                                     $K_update_time,
                                     {dataVersion}
                                 );
            ";
                keyValuePairs.Add("$K_report_no", teshu_Gas.Report_no);
                keyValuePairs.Add("$K_well_no", teshu_Gas.Well_no);
                keyValuePairs.Add("$K_well_deep", teshu_Gas.Well_deep);
                keyValuePairs.Add("$K_sample_temperature", teshu_Gas.Sample_temperature);
                keyValuePairs.Add("$K_top_boundary", teshu_Gas.Top_boundary);
                keyValuePairs.Add("$K_bottom_boundary", teshu_Gas.Bottom_boundary);
                keyValuePairs.Add("$K_oil_pressure", teshu_Gas.Oil_pressure);
                keyValuePairs.Add("$K_casing_pressure", teshu_Gas.Casing_pressure);
                keyValuePairs.Add("$K_sampling_location", teshu_Gas.Sampling_location);
                keyValuePairs.Add("$K_client", teshu_Gas.Client);
                keyValuePairs.Add("$K_sampler", teshu_Gas.Sampler);
                keyValuePairs.Add("$K_analyst", teshu_Gas.Analyst);
                keyValuePairs.Add("$K_sampling_unit", teshu_Gas.Sampling_unit);
                keyValuePairs.Add("$K_sampling_time", teshu_Gas.Sampling_time);
                keyValuePairs.Add("$K_update_real_name", teshu_Gas.Proofread_real_name);
                keyValuePairs.Add("$K_update_time", teshu_Gas.Proofread_time);
            }

            string error = null;
            int count = ExecSqlCmd(sql, keyValuePairs, c =>
            {
                return c.ExecuteNonQuery();
            }, ex => { error = ex.Message; });
            return count > 0 ? new ResultSuccess("修改成功") : new Result("修改失败," + error);
        }

        /// <summary>
        /// 根据主键获取一条
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-15 17:56:59。作者：王浩力
        public Teshu_gas Get(long id)
        {
            string sql = $" select  *  from  teshu_gas  where  id={id}  ";
            return ExecSqlCmd(sql, null, c =>
            {
                var reader = c.ExecuteReader();
                if (!reader.HasRows)
                {
                    return null;
                }
                if (reader.Read())
                {
                    return ReaderToField(reader);
                }
                return null;
            });

        }

        public PageModel<Teshu_gas> Page(Teshu_gas where, int p, int rows)
        {
            PageModel<Teshu_gas> pageModel = new PageModel<Teshu_gas>();
            pageModel.PageSize = rows;
            pageModel.PageIndex = p;

            Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
            StringBuilder whereSB = new StringBuilder();
            if (where != null)
            {
                if (!string.IsNullOrWhiteSpace(where.Report_no))
                {
                    whereSB.AppendLine("  and  Report_no  like  $Report_no ");
                    keyValuePairs.Add("$Report_no", "%" + where.Report_no + "%");
                }
                if (!string.IsNullOrWhiteSpace(where.E3) && DateTime.TryParse(where.E3, out DateTime d1))
                {
                    whereSB.AppendLine($"  and  input_time>='{d1.ToString("yyyy-MM-dd")}'    ");
                }
                if (!string.IsNullOrWhiteSpace(where.E4) && DateTime.TryParse(where.E4, out DateTime d2))
                {
                    whereSB.AppendLine($"  and  input_time<='{d2.ToString("yyyy-MM-dd")}'    ");
                }

                //步骤值查询 //添加时间：2022-12-29 17:33:30
                if (where.WorkList?.Count > 0)
                {
                    List<string> stepList = new List<string>();
                    foreach (var item in where.WorkList)
                    {
                        stepList.Add($"  o_step={item} ");
                    }
                    string step = $"  and  ({ string.Join(" or  ", stepList)  })  ";
                    whereSB.AppendLine(step);
                }
            }

            //总记录数
            string sql = "select   count(0) from  Teshu_gas  where  del_time is null  " + whereSB.ToString();
            pageModel.Total = ExecSqlCmd(sql, keyValuePairs, c =>
            {
                var obj = c.ExecuteScalar();
                if (obj != null)
                {
                    return (int)obj.ToString().ToMyDecimal();
                }
                return 0;
            });

            string sql2 = @$"select  *,
(select check_user_name from teshu_gas_check_history where teshu_gas_key=c.id  order by id desc limit 1) as check_user_name   
,(select check_time           from teshu_gas_check_history where teshu_gas_key=c.id  order by id desc limit 1) as check_time   
   
from  Teshu_gas AS c where   del_time is null   " + whereSB.ToString() +
               $"  order by  id  desc  limit   {rows}  offset  {(p - 1) * rows}  ";
            string error = null;
            pageModel.List = base.ExecSqlCmd(sql2, keyValuePairs, c =>
            {
                var reader = c.ExecuteReader();
                if (!reader.HasRows)
                {
                    return null;
                }
                List<Teshu_gas> list = new List<Teshu_gas>();
                while (reader.Read())
                {
                    Teshu_gas info = ReaderToField(reader);
                    if (info != null)
                    {
                        info.E3 = reader["check_user_name"].ToString();
                        info.E4 = reader["check_time"].ToString();
                        list.Add(info);
                    }
                }

                return list;
            }, ex => { error = ex.Message; });
            return pageModel;
        }

        private static Teshu_gas ReaderToField(System.Data.Common.DbDataReader reader)
        {
            Teshu_gas teshu_Gas = new Teshu_gas();
            teshu_Gas.Id = (long)reader["Id"].ToMyInt64();
            teshu_Gas.Report_no = reader["Report_no"].ToString();
            teshu_Gas.Well_no = reader["Well_no"].ToString();

            teshu_Gas.Well_deep = Convert.ToString(reader["Well_deep"]);
            teshu_Gas.Sample_temperature = reader["Sample_temperature"].ToMyDecimal();

            teshu_Gas.Top_boundary = reader["Top_boundary"].ToString();
            teshu_Gas.Bottom_boundary = reader["Bottom_boundary"].ToString();

            teshu_Gas.Oil_pressure = reader["Oil_pressure"].ToMyDecimal();
            teshu_Gas.Casing_pressure = reader["Casing_pressure"].ToMyDecimal();

            teshu_Gas.Sampling_location = reader["Sampling_location"].ToString();
            teshu_Gas.Client = reader["Client"].ToString();
            teshu_Gas.Sampler = reader["Sampler"].ToString();
            teshu_Gas.Analyst = reader["Analyst"].ToString();
            teshu_Gas.Sampling_unit = reader["Sampling_unit"].ToString();
            teshu_Gas.Sampling_time = reader["Sampling_time"].ToString();
            teshu_Gas.Input_real_name = reader["Input_real_name"].ToString();
            teshu_Gas.Input_user_id = (long)reader["Input_user_id"].ToMyInt64();
            teshu_Gas.Input_time = reader["Input_time"].ToString();
            teshu_Gas.Del_time = reader["Del_time"].ToString();
            teshu_Gas.Proofread_real_name = reader["Proofread_real_name"].ToString();
            teshu_Gas.Proofread_time = reader["Proofread_time"].ToString();
            teshu_Gas.O_step = Convert.ToByte(reader["O_step"]);

            //校对人id。//创建时间：2023-1-8 23:57:42
            teshu_Gas.Proofread_user_id = reader["Proofread_user_id"].ToMyInt64();
            return teshu_Gas;
        }

        /// <summary>
        /// 审核处理
        /// </summary>
        /// <param name="history"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-22 14:08:39
        public IResult Check(Teshu_gas_check_history history)
        {
            //修改步骤值
            int step = 4;
            if (history.Check_stat == 0)
            {
                step = 3;//驳回
            }
            string sql = $"  update  teshu_gas  set  o_step={step}  where  id={history.Teshu_gas_key}  ;";

            Dictionary<string, object> dict = new Dictionary<string, object>();
            Snowflake snowflake = new Snowflake(1, 1);
            //记录审核历史
            sql += @$" INSERT INTO teshu_gas_check_history (
                                        id,
                                        check_user_name,
                                        check_user_id,
                                        check_time,
                                        check_stat,
                                        reject_reason,
                                        teshu_gas_key
                                    )
                                    VALUES (
                                        { snowflake.NextId() },
                                        $check_user_name,
                                        $check_user_id,
                                        $check_time,
                                        $check_stat,
                                        $reject_reason,
                                        $teshu_gas_key
                                    ); ";
            dict.Add("$check_user_name", history.Check_user_name);
            dict.Add("$check_user_id", history.Check_user_id);
            dict.Add("$check_time", history.Check_time);
            dict.Add("$check_stat", history.Check_stat);
            dict.Add("$reject_reason", history.Reject_reason);
            dict.Add("$teshu_gas_key", history.Teshu_gas_key);
            string error = null;
            int count = ExecSqlCmd(sql, dict, c =>
            {
                return c.ExecuteNonQuery();
            }, ex => { error = ex.Message; });

            return count > 0 ? new ResultSuccess("审核成功") : new Result("审核失败");
        }
    }
}
